import { Text, StyleSheet, View, Image, TouchableOpacity, TouchableHighlight, Platform, PermissionsAndroid } from "react-native";
import React, { useState, useEffect, useRef } from "react";
import PropTypes from "prop-types";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { launchCamera, launchImageLibrary } from "react-native-image-picker";
import Popup from "./Popup";

ImagePicker.propTypes = {
  // 图片上传数量
  count: PropTypes.number,
  // 图片剪裁、缩放的模式
  mode: PropTypes.string,
  // 限制图片上传大小
  maxImageSize: PropTypes.number,
  // 上传图片的容器间距
  margin: PropTypes.number,

}

ImagePicker.defaultProps = {
  count: 2,
  mode: "contain",
  maxImageSize: 5,
  margin: 18,
}


export default function ImagePicker(props) {
  const { count, maxImageSize, onChange } = props;

  const [storage, setStorage] = useState(false);
  const [list, setList] = useState([]);
  const typeRef = useRef(null);

  const isAndroid = Platform.OS === "android";
  const insets = useSafeAreaInsets();
  const clearImage = "";
  const photoImage = "";

  useEffect(() => {
    if (isAndroid) {
      requestPermissions();
    }
  }, []);
  // 安卓权限获取
  const requestPermissions = async () => {
    try {
      const CAMERA = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.CAMERA,
        {
          title: '是否授权相机权限',
          message: '请确认授权，否则无法正常上传图片',
          buttonNegative: '取消',
          buttonPositive: '确定'
        }
      );
      const storage = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
      );
      setStorage(storage == PermissionsAndroid.RESULTS.GRANTED);
      if (CAMERA !== PermissionsAndroid.RESULTS.GRANTED) {
        showPermissionsTip();
      }
      return CAMERA;
    } catch (error) {
      return null;
    }
  }

  const showPermissionsTip = () => {
    $dialog.showDialog({
      type: "alert",
      title: "提示",
      content: "请在设置中授权相机权限，否则无法正常上传图片",
    });
  }

  const showType = async () => {
    if (isAndroid) {
      const res = await requestPermissions();
      if (res !== PermissionsAndroid.RESULTS.GRANTED) {
        return;
      }
    }
    typeRef && typeRef.current.show();
  }

  const choseType = (val) => {
    if (val === "cancel") {
      typeRef.current.hidden();
      $toast.showToast({ title: "您取消了上传图片" });
      return
    }
    typeRef.current.hidden();
    getImage(val);
  }

  getImage = async (type) => {
    if (type === "camera") {
      const timer = setTimeout(async () => {
        const result = await launchCamera({
          mediaType: "photo",
          cameraType: "back",
          saveToPhotos: isAndroid ? storage : true,
        });
        clearTimeout(timer);
        if (result.errorCode) {
          if (result.errorCode === "camera_unavailable") {
            $toast.showToast({ title: "相机在设备上不可用" });
            return;
          }
          if (result.errorCode === "permission") {
            showPermissionsTip();
            return;
          }
          return;
        }
        disposeResult(result);
      }, 200);
      return;
    }
    if (type === "image") {
      const result = await launchImageLibrary({
        mediaType: "photo",
      });
      disposeResult(result);
    }
  }

  const disposeResult = (result) => {
    if (result.didCancel) {
      $toast.showToast({ title: "您取消了上传图片" });
      return;
    }
    if (result.assets) {
      const { width, height, fileSize, uri } = result.assets[0];
      if (fileSize >= 1024 * 1024 * maxImageSize) {
        $toast.showToast({ title: `上传图片不能超过${maxImageSize}M` });
        return;
      }
      onChange && onChange([...list, uri]);
      setList([...list, uri]);
    }
  }

  const delImage = (index) => {
    const list = [...list];
    list.splice(index, 1);
    onChange && onChange(list);
    setList(list);
  }

  return (
    <View>
      <View style={styles.container}>
        {
          list.map((item, index) => (
            <View style={[styles.listContainer, { position: "relative", marginLeft: index === 0 ? 0 : 18, }]} key={index}>
              <TouchableOpacity style={{ flex: 1 }} onPress={() => { }}>
                <Image
                  style={{ width: 90, height: 90 }}
                  source={{ uri: item }}
                  resizeMode={props.mode}
                />
              </TouchableOpacity>
              <TouchableOpacity style={styles.clearContainer} onPress={() => { delImage(index) }}>
                <Image source={{ uri: clearImage }} style={{ width: 20, height: 20 }}></Image>
              </TouchableOpacity>
            </View>
          ))
        }
        {
          list.length < count ?
            <View style={[styles.listContainer, { marginLeft: list.length !== 0 && count >= 2 ? 18 : 0 }]}>
              <TouchableOpacity style={styles.listContent} onPress={showType}>
                <Image source={{ uri: photoImage }} style={{ width: 24, height: 24 }}></Image>
              </TouchableOpacity>
            </View> : <></>
        }
      </View>
      {/* 选择拍照或相册 */}
      <Popup position="bottom" borderRadius={10} insetBottom={false} ref={typeRef}>
        <View style={{ backgroundColor: "#F7F7F7", ...styles.typeBorderRadius }}>
          <TouchableHighlight style={styles.typeBorderRadius} onPress={() => { choseType("camera") }}>
            <View style={[styles.typeList, styles.typeLine, styles.typeBorderRadius]}>
              <Text style={styles.typeText}>拍照</Text>
            </View>
          </TouchableHighlight>
          <TouchableHighlight onPress={() => { choseType("image") }}>
            <View style={styles.typeList}>
              <Text style={styles.typeText}>从手机相册选择</Text>
            </View>
          </TouchableHighlight>
          <TouchableHighlight style={{ marginTop: 6 }} onPress={() => { choseType("cancel") }}>
            <View>
              <View style={styles.typeList}>
                <Text style={styles.typeText}>取消</Text>
              </View>
              <View style={{ height: insets.bottom, backgroundColor: "#ffffff" }}></View>
            </View>
          </TouchableHighlight>
        </View>
      </Popup>
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
    flexWrap: 'wrap',
  },
  listContainer: {
    width: 90,
    height: 90,
    borderRadius: 12,
    backgroundColor: "#F4F6F8",
  },
  listContent: {
    flex: 1,
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
  },
  typeList: {
    width: "100%",
    height: 52,
    flexDirection: "row",
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#fff",
  },
  typeText: {
    fontSize: 16,
    color: "#1A1A1A",
    fontWeight: "300",
  },
  typeLine: {
    borderBottomColor: "#E5E5E5",
    borderBottomWidth: 1
  },
  typeBorderRadius: {
    borderTopLeftRadius: 10,
    borderTopRightRadius: 10
  },
  clearContainer: {
    position: "absolute",
    right: 4,
    top: 4,
  }
})
